package com.ptu.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 数据库连接工具类
 */
public class DBUtil {

    private static SqlSessionFactory factory;

    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    static {
        InputStream is = null;
        try {
            //解析 mybatis.xml 文件
            is = Resources.getResourceAsStream("mybatis.xml");
            //获取 SqlSessionFactory
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取 SqlSession 对象
    public static SqlSession getSqlSession() {
        //获取 ThreadLocal 中的 SqlSession 对象
        SqlSession sqlSession = tl.get();

        if(sqlSession == null) {
            sqlSession = factory.openSession(true);

            //把创建好的对象放入 ThreadLocal 中
            tl.set(sqlSession);
        }

        return tl.get();
    }

    //关闭 SqlSession
    public static void closeAll() {
        SqlSession sqlSession = tl.get();

        if (sqlSession != null) {
            sqlSession.close();
        }

        tl.set(null);
    }
}
